<template>
  <div class="sjplatformSelectForm">
    <el-form :inline="true">
      <el-form-item label="姓名：">
        <el-input v-model="userTable.queryCondition.realName" placeholder="请输入姓名..." />
      </el-form-item>
      <el-form-item label="所属机构：">
        <el-tree-select v-model="userTable.queryCondition.orgName" :data="orgTreeData" check-strictly
          :render-after-expand="false" @node-click="handleNodeClick" placeholder="请选择..." />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="openEditForm('add', null)">新增</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="sjplatformtable">
    <el-table :data="userTable.tableData" v-loading="loading" empty-text="暂无数据！" stripe border style="width: 100%">
      <el-table-column type="expand">
        <template #default="{ row }">
          <el-form label-width="100px" :model="row" disabled>
            <el-form-item label="用户Id：">
              <span>{{ row.id }}</span>
            </el-form-item>
            <el-form-item label="用户名称：">
              <span>{{ row.realName }}</span>
            </el-form-item>
            <el-form-item label="登录账号：">
              <span>{{ row.loginName }}</span>
            </el-form-item>
            <el-form-item label="机构Id：">
              <span>{{ row.orgId }}</span>
            </el-form-item>
            <el-form-item label="机构名称：">
              <span>{{ row.orgName }}</span>
            </el-form-item>
            <el-form-item label="添加时间：">
              <span>{{ row.addTime }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 + (currentPage - 1) * pageSize }}
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="姓名" width="100" />
      <el-table-column prop="orgName" label="所属机构" class-name="left-align">
        <template #default="{ row }">
          <el-tooltip class="item" effect="light" :content="row.orgName" placement="top">
            <span>{{ row.orgName }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="{ row }">
          <span>{{ row.sex === 1 ? "男" : "女" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="birthday" label="出生日期" width="140">
        <template #default="row">
          <span>{{ commonUtil.Methods.formatDate(row.row.birthday) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="row">
          <el-tooltip content="配置角色" placement="bottom" effect="light">
            <i class="setting-icon" @click="configRole(row)"></i>
          </el-tooltip>
          <el-tooltip content="修改" placement="bottom" effect="light">
            <i class="edit-icon" @click="openEditForm('edit', row)"></i>
          </el-tooltip>
          <el-tooltip content="删除" placement="bottom" effect="light">
            <i class="del-icon" @click="handleDelete(row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next" :total="userTable.total" :page-size="pageSize" :current-page="currentPage"
      @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="newUserTableVisible" :title="formTitle" :destroy-on-close="true" width="50%" draggable>
    <UserAddOrUpdate />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="operateUser">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="newUserRoleVisible" :title="formTitle" :destroy-on-close="true" width="50%" draggable>
    <UserRole :userId="userId" :realName="realName" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelRole">取消</el-button>
        <el-button type="primary" @click="operateUserRole">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import UserAddOrUpdate from "./UserAddOrUpdate.vue";
import UserRole from './UserRole.vue';
import { useOrgTree } from "../../../hooks/SystemManager/Org/useOrgTree";
import commonUtil from "../../../utils/common";
import { useUserTable } from "../../../hooks/SystemManager/User/useUserTable";

let currentPage = ref(1);
let pageSize = ref(10); // 默认每页大小
let formTitle = ref("新增用户");
let loading = ref(false);

let newUserTableVisible = ref(false); //新增机构窗口
let addOrUpdate = ref("add"); //新增还是修改

let newUserRoleVisible = ref(false);//角色配置窗口
let userId = ref('');//配置角色窗口使用
let realName = ref('');//配置角色窗口使用

// 机构树
let { data, orgStore, fetchData } = useOrgTree();
fetchData(); // 调用数据获取方法
let orgTreeData = data;

let { userTable, userStore, queryData, addData, updateData, deleteData, configureUserRoles } = useUserTable(
  currentPage,
  pageSize
);
queryData();

function handleNodeClick(node) {
  console.log(node.id);
  userTable.queryCondition.orgId = node.id;
};
watch(
  () => orgStore.selectedOrgNode?.id,
  (newId) => {
    userTable.queryCondition.orgId = newId;
    searchData();
  }
);

//配置角色
function configRole(user) {
  newUserRoleVisible.value = true;
  formTitle.value = "配置角色";
  userId.value = user.row.id;
  realName.value = user.row.realName;
  userStore.userModel.roleIds = [];
  userStore.userModel.roleNames = [];
}
//打开编辑窗口
function openEditForm(value, data) {
  addOrUpdate.value = value;
  if (value == "add") {
    formTitle.value = "新增用户";
    userStore.resetUserModel();
  }
  if (value == "edit") {
    formTitle.value = "修改用户";
    userStore.userModel = data.row;
    // console.log(userStore.userModel);
  }
  newUserTableVisible.value = true;
};

//翻页事件
function handleCurrentChange(newPage) {
  currentPage.value = newPage;
  queryData(); // 根据当前页获取数据
};
//新增或修改
async function operateUser() {
  if (addOrUpdate.value == "add") {
    if (await addData()) {
      commonUtil.Methods.ShowMessage("success", "新增用户成功！");
      newUserTableVisible.value = !newUserTableVisible.value;
    } else {
      commonUtil.Methods.ShowMessage("Oops", "新增用户失败！");
    }
  }
  if (addOrUpdate.value == "edit") {
    if (await updateData()) {
      commonUtil.Methods.ShowMessage("success", "修改用户成功！");
      newUserTableVisible.value = !newUserTableVisible.value;
    } else {
      commonUtil.Methods.ShowMessage("Oops", "修改用户失败！");
    }
  }
  searchData();
};
//删除
async function handleDelete(data) {
  if (await deleteData(data.row.id)) {
    commonUtil.Methods.ShowMessage("success", "删除用户成功！");
  } else {
    commonUtil.Methods.ShowMessage("Oops", "删除用户失败！");
  }
  searchData();
};
//重置按钮
function reset() {
  userStore.resetUserModel();
};
function cancel() {
  userStore.resetUserModel();
  newUserTableVisible.value = !newUserTableVisible.value;
};
//配置角色
function operateUserRole() {
  configureUserRoles(userId.value, userStore.userModel.roleIds.join(','));
  newUserRoleVisible.value = !newUserRoleVisible.value;
}

//取消角色配置
const cancelRole = () => {
  newUserRoleVisible.value = !newUserRoleVisible.value;
};
//查询按钮
function searchData() {
  loading.value = true;
  currentPage.value = 1;
  queryData();
  loading.value = false;
};
</script>